/*
 * @Author: Qimu
 * @Date: 2020-04-19 05:46:51
 * @LastEditors: Qimu
 * @LastEditTime: 2020-06-23 02:24:10
 * @Description: file content
 * @FilePath: \vue-admin-koa2\koa2_api\module\middleware\refreshToken.js
 */
const tools = require('../utlis/tools');
const User = require('../schama/admin');
const query = require('../utlis/query');
const config = require('../config/config');
const jwt = require('jsonwebtoken');//签发Token

const refreshToken = {
  admin: () => {
    return async (ctx, next) => {
      // let token = ctx.request.header.authorization;
      // console.log('refreshToken', ctx.request.header.authorization);
      let decode = jwt.decode(ctx.request.header.authorization.split(' ')[1], config.accessJwt.secret);//解析jwt payload数据
      // console.log('refreshTokendecode', decode);
      let payload = {
        id: decode._id,
        username: decode.username,
        avatar: decode.avatar,
      }
      const token = await tools.signToken(payload, config.accessJwt.secret, config.accessJwt.expiresIn);//生成access-token
      // console.log('refreshToken-------->', token);
      ctx.body = {
        'data': {
          'token': token,
        },
        'meta': {
          'status': 200,
          'message': 'Token刷新成功!'
        }
      }
      await next();
    }
  }
}

module.exports = refreshToken;